package com.zx.sdk.league.member.sigmob;

import android.app.Activity;
import android.content.Context;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sigmob.sdk.base.j;
import com.sigmob.windad.Splash.WindSplashAD;
import com.sigmob.windad.Splash.WindSplashADListener;
import com.sigmob.windad.Splash.WindSplashAdRequest;
import com.sigmob.windad.WindAdBiddingLossReason;
import com.sigmob.windad.WindAdError;
import com.sigmob.windad.WindAdOptions;
import com.sigmob.windad.WindAds;
import com.sigmob.windad.newInterstitial.WindNewInterstitialAd;
import com.sigmob.windad.newInterstitial.WindNewInterstitialAdListener;
import com.sigmob.windad.newInterstitial.WindNewInterstitialAdRequest;
import com.sigmob.windad.rewardVideo.WindRewardAdRequest;
import com.sigmob.windad.rewardVideo.WindRewardInfo;
import com.sigmob.windad.rewardVideo.WindRewardVideoAd;
import com.sigmob.windad.rewardVideo.WindRewardVideoAdListener;
import com.zx.sdk.ZxSDK;
import com.zx.sdk.league.member.BaseLeagueMember;
import com.zx.sdk.listener.BaseZxRewardListener;
import com.zx.sdk.listener.BaseZxSplashListener;
import com.zx.sdk.model.AdInfo;
import com.zx.sdk.model.ReadyAdPosition;
import com.zx.sdk.model.ZxError;
import com.zx.sdk.util.LogHelper;

import java.util.HashMap;
import java.util.Map;

public class Sigmob extends BaseLeagueMember<Object, Object, Object, WindNewInterstitialAd, Object> {

    @Override
    public String getName() {
        return "sig";
    }

    @Override
    protected void onInit(Context context, String appId, boolean initialized) {
        if (initialized) return;
        WindAds ads = WindAds.sharedAds();
        ads.setUserAge(18);
        // useMediation:true 代表使用聚合服务;false: 代表单接 SigMob
        String appKey = appId.split("@@")[1];
        String realAppId = appId.split("@@")[0];
        ads.startWithOptions(context, new WindAdOptions(realAppId, appKey));
    }

    @Override
    protected void onLoadSplash(AdInfo adInfo, ViewGroup container, String mode, String type, BaseZxSplashListener listener) {
        if (AdInfo.AD_TYPE_EXPRESS_INTERSTITIAL_AD == adInfo.getAdType()) {
            onLoadInterstitial((Activity) container.getContext(), adInfo, mode, type, new BaseZxRewardListener() {
                @Override
                public void onADClick() {
                    listener.onADClicked();
                }

                @Override
                public void onADClose() {
                    listener.onADDismissed();
                }

                @Override
                public void onADExpose() {
                    listener.onADExposure();
                }

                @Override
                public void onADLoad() {
                    listener.onADLoaded(0L);
                }

                @Override
                public void onReward(@NonNull Map<String, Object> map) {

                }

                @Override
                public void onVideoCached() {

                }

                @Override
                public void onVideoComplete() {

                }

                @Override
                public void onPreLoadADError(ZxError error) {
                    listener.onPreLoadNoAD(error);
                }

                @Override
                public void onRewardStepVerify(int taskType, int currentTaskStatus) {

                }

                @Override
                public void onAdSkip(float v) {

                }

                @Override
                public void onVideoPlayError(ZxError error) {
                }

                @Override
                public void onNoAD(ZxError error) {
                    listener.onNoAD(error);
                }

                @Override
                public void onPreloading() {
                    listener.onPreloading();
                }

                @Override
                public void onLoaded() {
                    listener.onLoaded();
                }
            });
            return;
        }
        WindSplashAdRequest splashAdRequest = new WindSplashAdRequest(adInfo.getMapPid(), "", null);
        // 广告结束，广告内容是否自动隐藏.默认是false * 若开屏和应用共用Activity，建议false。* 若开屏是单独Activity ，建议true。
        splashAdRequest.setDisableAutoHideAd(true);
        // 广告允许最大等待返回时间
        splashAdRequest.setFetchDelay(2);
        // 设置开屏应用LOGO区域 设置此项开屏会默认使用Window渲染
        // splashAdRequest.setAppTitle(appTitle);
        // 设置开屏应用LOGO描述
        // splashAdRequest.setAppDesc(appDesc);
        WindSplashAD[] mWindSplashADContainer = new WindSplashAD[1];
        mWindSplashADContainer[0] = new WindSplashAD(splashAdRequest, new WindSplashADListener() {
            @Override
            public void onSplashAdShow(String s) {
                listener.onADExposure(Sigmob.this, adInfo);
            }

            @Override
            public void onSplashAdLoadSuccess(String s) {
                listener.onADLoaded(Sigmob.this, -1, adInfo);
                if (ZxSDK.FETCH_ONLY.equals(mode)) {
                    saveSplash(adInfo.getMapPid(), mWindSplashADContainer[0], container);
                }
            }

            @Override
            public void onSplashAdLoadFail(WindAdError windAdError, String s) {
                switch (mode) {
                    case ZxSDK.FETCH_ONLY:
                        listener.onPreLoadNoAD(Sigmob.this, new ZxError(String.valueOf(windAdError.getErrorCode()), windAdError.getMessage()), adInfo);
                        break;
                    case ZxSDK.FETCH_AND_SHOW:
                        listener.onNoAD(Sigmob.this, new ZxError(String.valueOf(windAdError.getErrorCode()), windAdError.getMessage()), adInfo);
                        break;
                }
            }

            @Override
            public void onSplashAdShowError(WindAdError windAdError, String s) {
            }

            @Override
            public void onSplashAdClick(String s) {
                listener.onADClicked(Sigmob.this, adInfo);
            }

            @Override
            public void onSplashAdClose(String s) {
                listener.onADDismissed(Sigmob.this, adInfo);

            }

            @Override
            public void onSplashAdSkip(String s) {

            }
        });
        mWindSplashADContainer[0].setCurrency(WindAds.CNY);//设置币种
        switch (mode) {
            case ZxSDK.FETCH_ONLY:
                mWindSplashADContainer[0].loadAd();
                break;
            case ZxSDK.FETCH_AND_SHOW:
                mWindSplashADContainer[0].loadAndShow(container);
                break;
        }
    }

    @Override
    public boolean onShowSplash(AdInfo adInfo, ViewGroup container, @Nullable Object adv, BaseZxSplashListener listener) {
        if (adv instanceof WindSplashAD) {
            ((WindSplashAD) adv).show(container);
            return true;
        } else if (adv instanceof WindNewInterstitialAd) {
            ((WindNewInterstitialAd) adv).show(new HashMap<>());
            return true;
        }
        return false;
    }

    @Override
    public void onLoadReward(Activity context, AdInfo adInfo, String mode, String type, BaseZxRewardListener listener) {
        if (AdInfo.AD_TYPE_EXPRESS_INTERSTITIAL_AD == adInfo.getAdType()) {
            onLoadInterstitial(context, adInfo, mode, type, listener);
            return;
        }
        Map<String, Object> options = null;
        try {
            Gson gson = new Gson();
            options = gson.fromJson(gson.toJson(adInfo), new TypeToken<Map<String, Object>>() {
            }.getType());
        } catch (Exception ignored) {
        }
        WindRewardAdRequest request = new WindRewardAdRequest(adInfo.getMapPid(), ZxSDK.getUid(), options);
        WindRewardVideoAd windRewardVideoAd = new WindRewardVideoAd(request);
        windRewardVideoAd.setWindRewardVideoAdListener(new WindRewardVideoAdListener() {

            @Override
            public void onRewardAdLoadSuccess(String s) {
                listener.onADLoad(Sigmob.this, adInfo);
                if (windRewardVideoAd.isReady()) {
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY:
                            saveReward(adInfo.getMapPid(), windRewardVideoAd);
                            break;
                        case ZxSDK.FETCH_AND_SHOW:
                            windRewardVideoAd.show(new HashMap<>());
                            break;
                    }
                }
            }

            @Override
            public void onRewardAdPreLoadSuccess(String s) {

            }

            @Override
            public void onRewardAdPreLoadFail(String s) {

            }

            @Override
            public void onRewardAdPlayStart(String s) {
                listener.onADExpose(Sigmob.this, adInfo);
            }

            @Override
            public void onRewardAdPlayEnd(String s) {
                listener.onVideoComplete(Sigmob.this, adInfo);
            }

            @Override
            public void onRewardAdClicked(String s) {
                listener.onADClick(Sigmob.this, adInfo);
            }

            @Override
            public void onRewardAdClosed(String s) {

            }

            @Override
            public void onRewardAdRewarded(WindRewardInfo windRewardInfo, String s) {
                Map<String, Object> map = new HashMap<>();
                map.put("Id", adInfo.getMapPid());
                if (windRewardInfo.isReward()) {
                    listener.onReward(Sigmob.this, map, adInfo);
                } else {
                    listener.onADClose(Sigmob.this, adInfo);
                }
            }

            @Override
            public void onRewardAdLoadError(WindAdError windAdError, String s) {
                switch (mode) {
                    case ZxSDK.FETCH_ONLY:
                        listener.onPreLoadADError(Sigmob.this, new ZxError(String.valueOf(windAdError.getErrorCode()), windAdError.getMessage()), adInfo);
                        break;
                    case ZxSDK.FETCH_AND_SHOW:
                        listener.onNoAD(Sigmob.this, new ZxError(String.valueOf(windAdError.getErrorCode()), windAdError.getMessage()), adInfo);
                        break;
                }
            }

            @Override
            public void onRewardAdPlayError(WindAdError windAdError, String s) {
                listener.onVideoPlayError(Sigmob.this, new ZxError(String.valueOf(windAdError.getErrorCode()), windAdError.getMessage()), adInfo);

            }
        });
        windRewardVideoAd.setCurrency(WindAds.CNY);//设置币种
        windRewardVideoAd.loadAd();
    }

    @Override
    public boolean onShowReward(Activity context, AdInfo adInfo, @Nullable Object reward, BaseZxRewardListener listener) {
        if (reward instanceof WindNewInterstitialAd && onShowInterstitial(context, adInfo, (WindNewInterstitialAd) reward, listener)) {
            return true;
        } else if (reward instanceof WindRewardVideoAd) {
            ((WindRewardVideoAd) reward).show(new HashMap<>());
            return true;
        }
        return false;
    }

    @Override
    public void onLoadInterstitial(Activity context, AdInfo adInfo, String mode, String type, BaseZxRewardListener listener) {
        //placementId 必填,USER_ID,OPTIONS可不填，
        WindNewInterstitialAdRequest request = new WindNewInterstitialAdRequest(adInfo.getMapPid(), ZxSDK.getUid(), null);
        WindNewInterstitialAd adv = new WindNewInterstitialAd(request);
        adv.setWindNewInterstitialAdListener(new WindNewInterstitialAdListener() {

            //仅sigmob渠道有回调，聚合其他平台无次回调
            @Override
            public void onInterstitialAdPreLoadSuccess(String placementId) {

            }

            //仅sigmob渠道有回调，聚合其他平台无次回调
            @Override
            public void onInterstitialAdPreLoadFail(String placementId) {

            }

            @Override
            public void onInterstitialAdLoadSuccess(String placementId) {
                listener.onADLoad(Sigmob.this, adInfo);
                if (adv.isReady()) {
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY:
                            if (ZxSDK.SPLASH.equals(adInfo.getDisplay())) {
                                saveSplash(adInfo.getMapPid(), adv, null);
                            } else if (ZxSDK.REWARD.equals(adInfo.getDisplay())) {
                                saveReward(adInfo.getMapPid(), adv);
                            } else if (ZxSDK.INTERSTITIAL.equals(adInfo.getDisplay())) {
                                saveInterstitial(adInfo.getMapPid(), adv);
                            }
                            break;
                        case ZxSDK.FETCH_AND_SHOW:
                            adv.show(new HashMap<>());
                            break;
                    }
                }
            }

            @Override
            public void onInterstitialAdShow(String placementId) {
                listener.onADExpose(Sigmob.this, adInfo);
            }


            @Override
            public void onInterstitialAdClicked(String placementId) {
                listener.onADClick(Sigmob.this, adInfo);
            }

            @Override
            public void onInterstitialAdClosed(String placementId) {
                if (ZxSDK.REWARD.equals(adInfo.getDisplay())) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("Id", adInfo.getMapPid());
                    listener.onReward(Sigmob.this, map, adInfo);
                }
                listener.onADClose(Sigmob.this, adInfo);
            }

            /**
             * 加载广告错误回调
             * WindAdError 新插屏错误内容
             * placementId 广告位
             */
            @Override
            public void onInterstitialAdLoadError(WindAdError windAdError, String placementId) {
                switch (mode) {
                    case ZxSDK.FETCH_ONLY:
                        listener.onPreLoadADError(Sigmob.this, new ZxError(String.valueOf(windAdError.getErrorCode()), windAdError.getMessage()), adInfo);
                        break;
                    case ZxSDK.FETCH_AND_SHOW:
                        listener.onNoAD(Sigmob.this, new ZxError(String.valueOf(windAdError.getErrorCode()), windAdError.getMessage()), adInfo);
                        break;
                }
            }

            /**
             * 播放错误回调
             * WindAdError 新插屏错误内容
             * placementId 广告位
             */
            @Override
            public void onInterstitialAdShowError(WindAdError windAdError, String placementId) {
                listener.onVideoPlayError(Sigmob.this, new ZxError(String.valueOf(windAdError.getErrorCode()), windAdError.getMessage()), adInfo);
            }
        });
        adv.loadAd();
    }

    @Override
    public boolean onShowInterstitial(Activity context, AdInfo adInfo, @Nullable WindNewInterstitialAd interstitial, BaseZxRewardListener listener) {
        try {
            interstitial.show(new HashMap<>());
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public int getCpmByPid(String type, String pid) {
        int cpm = super.getCpmByPid(type, pid);
        try {
            switch (type) {
                case ZxSDK.SPLASH:
                    if (splashMap.containsKey(pid)) {
                        Object adv = splashMap.get(pid);
                        if (adv instanceof WindSplashAD) {
                            cpm = Integer.parseInt(((WindSplashAD) adv).getEcpm());
                        } else if (adv instanceof WindNewInterstitialAd) {
                            cpm = Integer.parseInt(((WindNewInterstitialAd) adv).getEcpm());
                        }
                    }
                case ZxSDK.REWARD:
                    if (rewardMap.containsKey(pid)) {
                        Object adv = rewardMap.get(pid);
                        if (adv instanceof WindRewardVideoAd) {
                            cpm = Integer.parseInt(((WindRewardVideoAd) adv).getEcpm());
                        } else if (adv instanceof WindNewInterstitialAd) {
                            cpm = Integer.parseInt(((WindNewInterstitialAd) adv).getEcpm());
                        }
                    }
                case ZxSDK.INTERSTITIAL:
                    if (interstitialMap.containsKey(pid)) {
                        cpm = Integer.parseInt(interstitialMap.get(pid).getEcpm());
                    }
            }
        } catch (Exception exception) {
            LogHelper.d("sigmob getCpmByPid exception " + exception.getMessage());
        }
        cpmCache.put(type + pid, cpm);
        return cpm;
    }

    @Override
    public void notifyBiddingWin(String type, String mapPid, @Nullable ReadyAdPosition loser) {
        Map<String, Object> map = new HashMap<>();
        int winCpm = getCpmByPid(type, mapPid);
        map.put(WindAds.AUCTION_PRICE, winCpm);//获胜价格，建议 Sigmob 渠道胜出后回传 Sigmob 原始出价。其他价格可能会影响实际的结算价格。
        if (loser != null) {
            map.put(WindAds.HIGHEST_LOSS_PRICE, loser.getCpm());//瀑布流胜出的次高价
        }
        map.put(WindAds.CURRENCY, WindAds.CNY);//汇率
        j ad = null;
        if (ZxSDK.REWARD.equals(type)) {
            Object adv = rewardMap.get(mapPid);
            if (adv instanceof WindRewardVideoAd) {
                ad = (j) adv;
            } else if (adv instanceof WindNewInterstitialAd) {
                ad = (j) adv;
            }
        } else if (ZxSDK.SPLASH.equals(type)) {
            Object adv = splashMap.get(mapPid);
            if (adv instanceof WindSplashAD) {
                ad = (j) adv;
            } else if (adv instanceof WindNewInterstitialAd) {
                ad = (j) adv;
            }
        } else if (ZxSDK.INTERSTITIAL.equals(type)) {
            ad = interstitialMap.get(mapPid);
        }
        if (ad == null) {
            return;
        }
        ad.sendWinNotificationWithInfo(map);
        ad.setBidEcpm(winCpm);
        LogHelper.d(getName(), "notifyBiddingWin", mapPid, String.valueOf(winCpm), map.toString());
    }

    @Override
    public void notifyBiddingLose(String type, String mapPid, ReadyAdPosition winner, ZxSDK.LoseReason reason) {
        Map<String, Object> map = new HashMap<>();
        map.put(WindAds.AUCTION_PRICE, winner.getCpm()); // 竞胜价格
        map.put(WindAds.CURRENCY, WindAds.CNY); //竞胜价格币种
        map.put(WindAds.LOSS_REASON, WindAdBiddingLossReason.LOSS_REASON_LOW_PRICE.getCode()); // 竞败原因
        map.put(WindAds.ADN_ID, getWinId(winner)); // 竞败平台
        j ad = null;
        if (ZxSDK.REWARD.equals(type)) {
            Object adv = rewardMap.get(mapPid);
            if (adv instanceof WindRewardVideoAd) {
                ad = (j) adv;
            } else if (adv instanceof WindNewInterstitialAd) {
                ad = (j) adv;
            }
        } else if (ZxSDK.SPLASH.equals(type)) {
            Object adv = splashMap.get(mapPid);
            if (adv instanceof WindSplashAD) {
                ad = (j) adv;
            } else if (adv instanceof WindNewInterstitialAd) {
                ad = (j) adv;
            }
        } else if (ZxSDK.INTERSTITIAL.equals(type)) {
            ad = interstitialMap.get(mapPid);
        }
        if (ad == null) {
            return;
        }
        ad.sendLossNotificationWithInfo(map);
        LogHelper.d(getName(), "notifyBiddingLose", mapPid, "出价", String.valueOf(getCpmByPid(type, mapPid)), "竞胜价", String.valueOf(winner.getCpm()), map.toString());
    }


    private String getWinId(ReadyAdPosition winner) {
        if ("bd".equals(winner.getLeague())) {
            return "5";
        } else if ("sig".equals(winner.getLeague())) {
            return "1";
        } else if ("qq".equals(winner.getLeague())) {
            return "3";
        } else if ("ks".equals(winner.getLeague())) {
            return "4";
        } else if ("mtg".equals(winner.getLeague())) {
            return "6";
        } else {
            return "10001";
        }
    }
}
